/** 
 * TextFinder.java
 * @author Lex
 * 2007-9-10 ����02:29:02
 */
package org.lex.notepad.ui.search;

import javax.swing.JTextArea;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.Position;
import javax.swing.text.Segment;

public class TextFinder {
	private JTextArea text = null;
	private Position.Bias direction = Position.Bias.Forward;
	private String target = "";

	public TextFinder(JTextArea component) {
		this.text = component;
	}

	public void setDirection(Position.Bias direction) {
		this.direction = direction;
	}

	public void setTarget(String target) {
		this.target = target;
	}

	public boolean findNext() {
		try {
			Document doc = text.getDocument();
			int pos = text.getCaretPosition();
			if (direction == Position.Bias.Backward)
				pos--;
			int length = doc.getLength();
			while (pos < length && pos >= 0) {
				int lineNo = text.getLineOfOffset(pos);
				int lineEnd = 0;
				if (direction == Position.Bias.Forward)
					lineEnd = text.getLineEndOffset(lineNo);
				else {
					lineEnd = pos;
					pos = text.getLineStartOffset(lineNo);
				}
				int index = isLineContainsTarget(doc, pos, lineEnd);
				if (-1 != index) {
					text.select(index, index + target.length());
					return true;
				}
				if (direction == Position.Bias.Forward)
					pos = lineEnd++;
				else
					pos--;
			}
			return false;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	Segment txt = new Segment();

	// start <= end
	private int isLineContainsTarget(Document doc, int start, int end) throws BadLocationException {
		doc.getText(start, end - start, txt);
		String str = txt.toString();
		int index = 0;
		if (direction == Position.Bias.Forward)
			index = str.indexOf(target);
		else
			index = str.lastIndexOf(target);
		if (-1 == index)
			return -1;
		return index + start;
	}

	void ln(Object... msg) {
		if (null == msg || 0 == msg.length) {
			System.out.println();
			return;
		}
		for (int i = 0; i < msg.length - 1; i++)
			System.out.print(msg[i]);
		System.out.println(msg[msg.length - 1]);
	}
}
